// pages/submit/submit.js
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    types: ["Rumor头条", "失物招领", "寻物启事"],
    what: 0, // 这个what是用来确定投稿类型的
    phs: [], // 这个数组存储的文件的路径，可以用于上传的时候使用
    cnt: 0, // 已经选择的图片的数量
    input: "", // 这个值利用了双向绑定机制，能够在输入的时候同时被改变
    code: "", //来自服务器的随机投稿码
    percents: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // 对应图片上传的百分比
    isFinished: true, //是否上传完成
    now: 0, // 现在正在上传的图片
    deleteNum: 0, // 用户删掉的图片数量，用这个做一个偏移值，避免名字的重复
    sp: String.fromCharCode(0x25bc), // 倒三角的特殊字符
    sort:[['rumorSubmit','deleteRumorImg','rumorImgUpload','getRumorCode'],['foundSubmit','deleteFoundImg','foundImgUpload','getFoundCode'],['lostSubmit','deleteLostImg','lostImgUpload','getLostCode']]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    // 请求一个投稿随机编码
    this.getCode()
    console.log(this.data.code)
    //提示用户离开页面不会做任何的保存
    wx.enableAlertBeforeUnload({
      message: "离开页面不会保存您的更改"
    })
  },

  /**
   * 获取投稿编码
   */
  getCode:function(){
    wx.request({
      url: 'https://www.scutwei.ltd/api/'+this.data.sort[this.data.what][3],
      method: 'GET',
      success: (res) => {
        console.log(res)
        if (res.data != null) {
          this.data.code = res.data
        }
      }
    })
  }
  ,

  /**
   * 获取本地图片并上传
   */
  choosePh: function () {
    if (this.data.cnt < 10) {
      wx.chooseImage({
        count: 10 - this.data.cnt,
        success: (res) => {
          this.setData({
            phs: this.data.phs.concat(res.tempFilePaths),
            cnt: this.data.cnt + res.tempFilePaths.length,
          })
          // 递归的上传
          this.upload()
        }
      })
    }
  },

  /**
   * 提交的事件，上传相应的内容。
   */
  submit: function () {
    //只有所有的图片都上传好了，才能提交——指定 isFinished 的值
    for (var i = 0; i < this.data.cnt; ++i) {
      if (this.data.percents[i] < 100) this.data.isFinished = false
      else this.data.isFinished = true
    }

    if (this.data.isFinished) {
      //确定提交
      wx.request({
        url: 'https://www.scutwei.ltd/api/'+this.data.sort[this.data.what][0],
        method: 'POST',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          remark: this.data.input,
          rumor_code: this.data.code,
          username: app.globalData.data.username,
          found_code:this.data.code,
          lost_code:this.data.code
        },
        success: res => {
          wx.showToast({
            title: '投稿成功',
          })
          console.log(res)
          //上传之后把页面清空
          this.setData({
            what: 0,
            phs: [],
            cnt: 0,
            input: "",
            code: "",
            percents: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            isFinished: true,
            now: 0
          })
        }
      })
    } else {
      wx.showToast({
        title: '还未上传完成',
      })
    }
  },

  /**
   * 上传图片的逻辑，每次上传好一张再继续上传下一张，递归调用
   */
  upload: function () {
    if (this.data.now < this.data.cnt) {
      wx.uploadFile({
        filePath: this.data.phs[this.data.now],
        name: 'content',
        url: 'https://www.scutwei.ltd/api/'+this.data.sort[this.data.what][2],
        header: {
          "Content-Type": "multipart/form-data",
          "accept": "application/json",
        },
        formData: {
          username: app.globalData.data.username,
          rumor_code: this.data.code,
          filename: this.data.code + "-" + (this.data.now + this.data.deleteNum)
        },
        success: (r) => {
          this.data.now++
          this.upload()
        }
      }).onProgressUpdate(res => { // 监听上传的进度
        this.data.percents[this.data.now] = res.progress
        console.log(res.progress)
        this.setData({
          percents: this.data.percents,
        })
      })
    }
  },

  // 删除图片的逻辑
  deletePh: function (e) {
    console.log(e)
    wx.showModal({
      cancelColor: 'cancelColor',
      title: '是否删除',
      success: (r) => {
        console.log(r)
        if (r.confirm) {
          wx.request({
            url: 'https://www.scutwei.ltd/api/'+this.data.sort[this.data.what][1],
            method: 'POST',
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
              username: app.globalData.data.username,
              rumor_code: this.data.code,
              filename: this.data.phs[e.currentTarget.dataset.index] + "-" + (e.currentTarget.dataset.index + this.data.deleteNum)
            },
            success: res => {
              if (res.data == 1) {
                this.data.phs.splice(e.currentTarget.dataset.index, 1)
                this.data.percents[e.currentTarget.dataset.index] = 0
                this.setData({
                    phs: this.data.phs,
                    cnt: this.data.cnt - 1,
                    now: this.data.now - 1,
                    percents: this.data.percents
                  })
                  ++this.data.deleteNum
              } else {
                wx.showToast({
                  title: '删除失败',
                })
              }
            }
          })
        }
      }
    })
  }
})